//
//  LYDebug.m
//  LYDevelopKit
//
//  Created by 李阳 on 2018/7/31.
//

#import "LYDebug.h"

static BOOL WindowLogEnable = NO;

static inline void FileLog(NSString *log, NSString *fileName)
{
    if (!log.length) return;
    
    NSString *document  = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)[0];
    NSString *filePath = [document stringByAppendingPathComponent:fileName.lastPathComponent];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    if(![fileManager fileExistsAtPath:filePath])
    {
        //如果不存在
        NSString *str = @"begin:========================";
        [str writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    }
    
    NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:filePath];
    [fileHandle seekToEndOfFile];  //将节点跳到文件的末尾
    
    static NSDateFormatter *fmt = nil;
    if (!fmt)
    {
        fmt = [[NSDateFormatter alloc] init];
        fmt.dateFormat = @"yyyy-MM-dd HH:mm:ss:SSS";
    }
    NSString *datestr = [fmt stringFromDate:[NSDate date]];
    NSString *str = [NSString stringWithFormat:@"\n%@\n%@",datestr,log];
    NSData* stringData  = [str dataUsingEncoding:NSUTF8StringEncoding];
    [fileHandle writeData:stringData]; //追加写入数据
    [fileHandle closeFile];
}


@interface LYLogTextView : UITextView
- (void)log:(NSString *)string;
- (void)logFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1,2);

- (void)clear;

@end

@interface LYLogTextView ()

@property (nonatomic, strong) NSDateFormatter *fmt;
@property (nonatomic, assign) uint64_t idx;


@end

@implementation LYLogTextView
{
    CGPoint startPoint;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (!self) return nil;
    
    [self setUp];
    
    return self;
}

- (void)awakeFromNib
{
    [super awakeFromNib];
    [self setUp];
}

/// 初始化
- (void)setUp
{
    _fmt = [[NSDateFormatter alloc] init];
    _fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
    _fmt.dateFormat = @"HH:mm:ss";
    
    self.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.4];
    self.textColor = [UIColor whiteColor];
    self.font = [UIFont systemFontOfSize:12];
    self.editable = NO;
//    self.selectable = NO;
    self.showsVerticalScrollIndicator = NO;
    self.showsHorizontalScrollIndicator = NO;
    self.layoutManager.allowsNonContiguousLayout = NO;
    
    [self addGestureRecognizer:[[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureHandler:)]];
}

- (void)panGestureHandler:(UIPanGestureRecognizer *)pan
{
    if (pan.state == UIGestureRecognizerStateBegan)
    {
        startPoint = [pan locationInView:self];
        [UIView animateWithDuration:0.25 animations:^{
            self.transform = CGAffineTransformMakeScale(1.1, 1.1);
            self.alpha = 0.7;
        }];
    }
    else if (pan.state == UIGestureRecognizerStateChanged)
    {
        CGPoint newPoint = [pan locationInView:self];
        CGFloat deltaX = newPoint.x-startPoint.x;
        CGFloat deltaY = newPoint.y-startPoint.y;
        self.center = CGPointMake(self.center.x+deltaX, self.center.y+deltaY);
        
//        CGPoint translation = [pan translationInView:self];
//
//        self.center = CGPointMake(self.center.x + translation.x, self.center.y + translation.y);
//
//        //关键，不设为零会不断递增，视图会突然不见
//        [pan setTranslation:CGPointZero inView:self];
    }
    else if (pan.state == UIGestureRecognizerStateEnded)
    {
        [UIView animateWithDuration:0.25 animations:^{
            self.transform = CGAffineTransformIdentity;
            self.alpha = 1.0;
        }];
    }
}

- (void)log:(NSString *)string
{
    NSString *time = [_fmt stringFromDate:[NSDate date]];
    
    NSString *append = _idx ? [NSString stringWithFormat:@"\n\n%llu. %@ %@", _idx, time, string] : [NSString stringWithFormat:@"%llu. %@ %@", _idx, time, string];
    self.text = [self.text stringByAppendingString:append];
    
    [self scrollRangeToVisible:NSMakeRange(0, self.text.length)];
    _idx++;
}
- (void)logFormat:(NSString *)format, ...
{
    NSCParameterAssert(format);
    va_list args;
    va_start(args, format);
    NSString *str = [[NSString alloc] initWithFormat:format arguments:args];
    va_end(args);
    [self log:str];
}

- (void)clear
{
    self.text = nil;
    _idx = 0;
}


@end


static inline LYLogTextView *LYLogView()
{
    static LYLogTextView *log_;
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    if (!log_ && keyWindow)
    {
        LYLogTextView *log = [[LYLogTextView alloc] initWithFrame:(CGRect){5, 80, 150, 150}];
        [keyWindow addSubview:log];
        log_ = log;
    }
    return log_;
}

static inline void WindowLog(NSString *string)
{
    [LYLogView() log:string];
}

//static inline void WindowLogFmt(NSString *format, ...)
//{
//    NSCParameterAssert(format);
//    va_list args;
//    va_start(args, format);
//    NSString *str = [[NSString alloc] initWithFormat:format arguments:args];
//    va_end(args);
//    WindowLog(str);
//}

static inline void ResetWindowLog(void)
{
    [LYLogView() clear];
}



@implementation LYDebug

+ (void)setWindowLogEnable:(BOOL)enable
{
    WindowLogEnable = enable;
}

+ (void)logToWindow:(NSString *)log
{
    if (!WindowLogEnable) return;
    WindowLog(log);
}

+ (void)logToWindowWithFormat:(NSString *)format, ...
{
    if (!WindowLogEnable) return;
    NSCParameterAssert(format);
    va_list args;
    va_start(args, format);
    NSString *str = [[NSString alloc] initWithFormat:format arguments:args];
    va_end(args);
    WindowLog(str);
}

+ (void)clearWindowLog
{
    if (!WindowLogEnable) return;
    ResetWindowLog();
}


+ (void)logToFile:(NSString *)log fileName:(NSString *)fileName
{
    FileLog(log, fileName);
}

@end



